import React, { useState } from 'react';
import {
  BrowserRouter as Router,
  Redirect,
  Route,
  Switch,
} from 'react-router-dom';
/* import {HashRouter as Router ,Redirect,Route,Switch} from 'react-router-dom' */
import { connect } from 'react-redux';
import loadable from 'react-loadable';

import { Spin } from 'antd';
/* 路由的动态加载 ,Loadable方法进行封装，动态传入路由地址，针对loader方法*/
function myLoadable(loader) {
  return loadable({
    loader,
    loading: function () {
      return (
        <div style={{ textAlign: 'center', paddingTop: '5vh' }}>
          <Spin tip="Loading..." size="large"></Spin>
        </div>
      );
    },
  });
}

const Login = myLoadable(() => import('./login'));
const NotFound = myLoadable(function () {
  return import('./common/NotFound');
});
const NotRight = myLoadable(function () {
  return import('./common/NotRight');
});
const Home = myLoadable(() => import('./home'));
const ProjectList = myLoadable(() => import('./project/List'));

const UserList = myLoadable(() => import('./user'));
const UserEdit = myLoadable(() => import('./user/Edit'));

/* import Login from './login'
import NotFound from './common/NotFound'
import NotRight from './common/NotRight'

import Home from './home' */

// 对Route进行封装
const RouteList = [
  { path: '/home', component: <Home /> },
  { path: '/project/list', component: <ProjectList /> },
  { path: '/user/list', component: <UserList /> },
  { path: '/user/edit', component: <UserEdit /> },
];

function App({ token }) {
  function hasLogin() {
    return !!token;
  }

  const [style, setStyle] = useState(false);

  return (
    <div
      className={style ? 'application-container red' : 'application-container'}
    >
      <Router>
        <Switch>
          <Route path="/403" component={NotRight} />
          <Route path="/404" component={NotFound} />
          <Route path="/login" component={Login} />
          {RouteList.map((it) => {
            return (
              <Route
                key={it.path}
                path={it.path}
                render={function () {
                  return hasLogin() ? it.component : <NotRight />;
                }}
              />
            );
          })}
          <Redirect path="/" to="/login" exact />
          <Redirect path="/" to="/404" />
        </Switch>
      </Router>
    </div>
  );
}
function mapStateToProps(state) {
  return {
    token: state.common.token,
  };
}
// connect方法的高阶组件实现了dispatch注入，mapStateToProps方法实现了两个功能 -> redux中的getState()和subscribe方法
export default connect(mapStateToProps)(App);
